package com.hjm.project.ShopOrder.ShopOrder.api;

import com.hjm.common.exception.BusinessException;
import com.hjm.project.ShopOrder.ShopOrder.api.util.ExpressBirdApiUtil;
import com.hjm.project.ShopOrder.ShopOrder.utils.JsonUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ExpressBirdApi {

    //电商ID
    private String EBusinessID="1642372";
    //电商加密私钥，快递鸟提供，注意保管，不要泄漏
    private String AppKey="cce0659c-8d35-4852-b320-432370a5224e";
    //请求url
    private String ReqURL="http://api.kdniao.com/api/dist";

    public static void main(String[] args) {
        ExpressBirdApi expressApi = new ExpressBirdApi();
        System.out.println(expressApi.getData("ZTO","75353570388316"));
    }


    /**
     * @Author maker
     * @Description 获取物流信息
     * @Param [name, num]
     * @return java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
     **/
    public List<Map<String, Object>> getData(String name,String num){
        List<Map<String, Object>> list = null;
        try{
            ExpressBirdApi api = new ExpressBirdApi();
            String result = api.getOrderTracesByJson(name, num);
            Map<String, Object> maps = JsonUtils.jsonToMap(result);
            if (maps.get("Traces") != null) {
                list = (List)maps.get("Traces");
                if (list == null || list.size() == 0) {
                    throw  new BusinessException("暂未查询到当前物流信息");
                }
                list.sort((a,b) -> cn.hutool.core.date.DateUtil.parse(a.get("AcceptTime").toString()).getTime() - cn.hutool.core.date.DateUtil.parse(b.get("AcceptTime").toString()).getTime() >= 0 ? -1 : 1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }


    /**
     * Json方式 查询订单物流轨迹
     * @throws Exception
     */
    public String getOrderTracesByJson(String expCode, String expNo) throws Exception{
        String requestData= "{'OrderCode':'','ShipperCode':'" + expCode + "','LogisticCode':'" + expNo + "'}";

        Map<String, String> params = new HashMap<String, String>();
        params.put("RequestData", urlEncoder(requestData, "UTF-8"));
        params.put("EBusinessID", EBusinessID);
        params.put("RequestType", "1002");
        String dataSign=encrypt(requestData, AppKey, "UTF-8");
        params.put("DataSign", urlEncoder(dataSign, "UTF-8"));
        params.put("DataType", "2");
        return ExpressBirdApiUtil.sendPost(ReqURL, params);
    }


    /**
     * base64编码
     * @param str 内容
     * @param charset 编码方式
     * @throws UnsupportedEncodingException
     */
    private String base64(String str, String charset) throws UnsupportedEncodingException{
        String encoded = ExpressBirdApiUtil.base64Encode(str.getBytes(charset));
        return encoded;
    }

    @SuppressWarnings("unused")
    private String urlEncoder(String str, String charset) throws UnsupportedEncodingException{
        String result = URLEncoder.encode(str, charset);
        return result;
    }

    /**
     * 电商Sign签名生成
     * @param content 内容
     * @param keyValue Appkey
     * @param charset 编码方式
     * @throws UnsupportedEncodingException ,Exception
     * @return DataSign签名
     */
    @SuppressWarnings("unused")
    private String encrypt (String content, String keyValue, String charset) throws UnsupportedEncodingException, Exception
    {
        if (keyValue != null)
        {
            return base64(ExpressBirdApiUtil.MD5(content + keyValue, charset), charset);
        }
        return base64(ExpressBirdApiUtil.MD5(content, charset), charset);
    }


}
